package com.mep.gateway.config;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class TokenGlobalFilter implements GlobalFilter, Ordered {

    /**
     * 不进行token校验的请求地址 可配置在配置文件中
     */
    @Value("#{'${ignoreUrlList}'.split(',')}")
    public List<String> ignoreUrlList;

    /**
     * 拦截所有的请求头
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求url
        String requestUrl = request.getPath().toString();
        Boolean canSkip = false;

        // 请求方式是OPTIONS的时候 跳过
        String method = request.getMethod().name();
        if (RequestMethod.OPTIONS.name().equals(method)) {
            canSkip = true;
        }
        if (!canSkip) {
            // 是否是不进行token校验的请求地址
            canSkip = !ignoreUrlList.parallelStream().filter(x -> requestUrl.contains(x)).collect(Collectors.toList())
                    .isEmpty();
        }
        if (canSkip) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            JSONObject message = new JSONObject();
            message.put("code", 401);
            message.put("msg", "无token");
            byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
//        LoginResult currentUser = this.getLoginResultByToken(token);
//        if (currentUser == null || currentUser.getData() == null || !currentUser.isSuccess()) {
//            JSONObject message = new JSONObject();
//            message.put("code", 401);
//            message.put("message", "无效token");
//            DataBuffer buffer = response.bufferFactory().wrap(bits);
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
//            return response.writeWith(Mono.just(buffer));
//        }
        // 将用户信息放到header中
//        String userInfo = "";
//        try {
//            // 为防止中文乱码 先编码
//            userInfo = URLEncoder.encode(JSON.toJSONString(currentUser), "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        ServerHttpRequest mutableReq = exchange.getRequest().mutate().header("token", token).build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
        return chain.filter(mutableExchange);

    }

    /**
     * 根据token获取用户信息
     *
     * @param token
     * @return LoginResult
     */
//    private LoginResult getLoginResultByToken(String token) {
//        // 根据token获取用户信息
//    }

    @Override
    public int getOrder() {
        return -200;
    }
}
